<template>
  <div id="categoryListPage">
    <div class="page-header">
      <h1 class="page-title">分类管理</h1>
      <a-button type="primary" @click="showAddModal" class="add-button">
        <template #icon><plus-outlined /></template>
        添加分类
      </a-button>
    </div>
    <div class="content">
      <div class="tree-container">
        <div class="section-title">
          <folder-outlined />
          <span>分类树</span>
        </div>
        <a-tree
          :tree-data="categoryList"
          :field-names="{ title: 'name', key: 'id', children: 'child' }"
          default-expand-all
          @select="handleSelect"
          class="category-tree"
        >
          <template #title="{ name, id }">
            <div class="category-item">
              <folder-outlined class="category-icon" />
              <span>{{ name }}</span>
            </div>
          </template>
        </a-tree>
      </div>
      <div class="info-container">
        <div class="section-title">
          <info-circle-outlined />
          <span>分类详情</span>
        </div>
        <template v-if="selectedCategory">
          <div class="info-card">
            <div class="info-header">
              <h2>{{ selectedCategory.name }}</h2>
              <div class="info-actions">
                <a-button type="primary" size="small" @click="handleInfoEdit">
                  <template #icon><edit-outlined /></template>
                  修改
                </a-button>
                <a-button type="primary" danger size="small" @click="handleDelete">
                  <template #icon><delete-outlined /></template>
                  删除
                </a-button>
              </div>
            </div>
            <div class="info-content">
              <div class="info-item">
                <span class="label">分类ID：</span>
                <span class="value">{{ selectedCategory.id }}</span>
              </div>
              <div class="info-item">
                <span class="label">分类名称：</span>
                <span class="value">{{ selectedCategory.name }}</span>
              </div>
              <div class="info-item">
                <span class="label">排序值：</span>
                <span class="value">{{ selectedCategory.sort }}</span>
              </div>
              <div class="info-item">
                <span class="label">子分类数量：</span>
                <span class="value">{{ selectedCategory.child.length }}</span>
              </div>
              <div class="info-item">
                <span class="label">父级分类：</span>
                <span class="value">{{ getParentName(selectedCategory.parentId) }}</span>
              </div>
            </div>
          </div>
        </template>
        <template v-else>
          <div class="empty-info">
            <inbox-outlined class="empty-icon" />
            <span>请选择一个分类查看详情</span>
          </div>
        </template>
      </div>
    </div>

    <a-modal
      v-model:visible="addModalVisible"
      title="添加分类"
      @ok="handleAdd"
      @cancel="handleCancel"
      :confirmLoading="addLoading"
    >
      <a-form
        :model="addForm"
        :rules="rules"
        ref="addFormRef"
        layout="vertical"
      >
        <a-form-item label="分类名称" name="name">
          <a-input v-model:value="addForm.name" placeholder="请输入分类名称" />
        </a-form-item>
        <a-form-item label="父级分类" name="parentId">
          <a-tree-select
            v-model:value="addForm.parentId"
            :tree-data="categoryList"
            :field-names="{ label: 'name', value: 'id', children: 'child' }"
            placeholder="请选择父级分类"
            tree-default-expand-all
            allow-clear
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal
      v-model:visible="editModalVisible"
      title="修改分类"
      @ok="handleEdit"
      @cancel="handleEditCancel"
      :confirmLoading="editLoading"
    >
      <a-form
        :model="editForm"
        :rules="rules"
        ref="editFormRef"
        layout="vertical"
      >
        <a-form-item label="分类名称" name="name">
          <a-input v-model:value="editForm.name" placeholder="请输入分类名称" />
        </a-form-item>
        <a-form-item label="父级分类" name="parentId">
          <a-tree-select
            v-model:value="editForm.parentId"
            :tree-data="categoryList"
            :field-names="{ label: 'name', value: 'id', children: 'child' }"
            placeholder="请选择父级分类"
            tree-default-expand-all
            allow-clear
          />
        </a-form-item>
        <a-form-item label="排序" name="sort">
          <a-input-number v-model:value="editForm.sort" :min="0" style="width: 100%" placeholder="请输入排序值" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { listAllCategory, addStore, modifyCategory, delCategory } from '@/api/category';
import { message, Modal } from 'ant-design-vue';
import type { FormInstance } from 'ant-design-vue';
import { 
  EditOutlined, 
  DeleteOutlined, 
  PlusOutlined, 
  FolderOutlined, 
  InfoCircleOutlined, 
  InboxOutlined 
} from '@ant-design/icons-vue';

interface Category {
  id: number;
  name: string;
  sort: number;
  parentId?: number;
  child: Category[];
}

const categoryList = ref<Category[]>([]);
const addModalVisible = ref(false);
const editModalVisible = ref(false);
const addFormRef = ref<FormInstance>();
const editFormRef = ref<FormInstance>();

const addForm = ref({
  name: '',
  parentId: undefined as number | undefined,
});

const editForm = ref({
  id: 0,
  name: '',
  parentId: undefined as number | undefined,
  sort: 0,
});

const rules = {
  name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
  parentId: [{ required: true, message: '请选择父级分类', trigger: 'change' }],
  sort: [{ required: true, message: '请输入排序值', trigger: 'blur' }],
};

const selectedCategory = ref<Category | null>(null);

const showAddModal = () => {
  addModalVisible.value = true;
};

const showEditModal = (id: number) => {
  const findCategory = (categories: Category[], targetId: number): Category | null => {
    for (const category of categories) {
      if (category.id === targetId) {
        return category;
      }
      const found = findCategory(category.child, targetId);
      if (found) {
        return found;
      }
    }
    return null;
  };

  const category = findCategory(categoryList.value, id);
  if (category) {
    editForm.value = {
      id: category.id,
      name: category.name,
      parentId: category.parentId,
      sort: category.sort,
    };
    editModalVisible.value = true;
  }
};

const addLoading = ref(false);
const editLoading = ref(false);

const handleAdd = () => {
  addFormRef.value?.validate().then(() => {
    addLoading.value = true;
    addStore({
      name: addForm.value.name,
      parentId: addForm.value.parentId || 0,
    }).then(res => {
      if (res.data.code === 200) {
        message.success('添加成功');
        addModalVisible.value = false;
        fetchCategoryList();
      } else {
        message.error(res.data.msg || '添加失败');
      }
    }).catch(error => {
      console.error('添加分类失败:', error);
      message.error('添加失败，请稍后重试');
    }).finally(() => {
      addLoading.value = false;
    });
  });
};

const handleEdit = () => {
  editFormRef.value?.validate().then(() => {
    editLoading.value = true;
    modifyCategory({
      id: editForm.value.id,
      name: editForm.value.name,
      parentId: editForm.value.parentId || 0,
      sort: editForm.value.sort,
    }).then(res => {
      if (res.data.code === 200) {
        message.success('修改成功');
        editModalVisible.value = false;
        fetchCategoryList();
      } else {
        message.error(res.data.msg || '修改失败');
      }
    }).catch(error => {
      console.error('修改分类失败:', error);
      message.error('修改失败，请稍后重试');
    }).finally(() => {
      editLoading.value = false;
    });
  });
};

const handleCancel = () => {
  addModalVisible.value = false;
  addFormRef.value?.resetFields();
};

const handleEditCancel = () => {
  editModalVisible.value = false;
  editFormRef.value?.resetFields();
};

const fetchCategoryList = async () => {
  try {
    const res = await listAllCategory();
    if (res.data.code === 200) {
      categoryList.value = res.data.data;
    } else {
      message.error(res.data.msg || '获取分类列表失败');
    }
  } catch (error) {
    console.error('获取分类列表失败:', error);
    message.error('获取分类列表失败，请稍后重试');
  }
};

const handleSelect = (selectedKeys: number[], info: { node: { dataRef: Category } }) => {
  selectedCategory.value = info.node.dataRef;
};

const getParentName = (parentId?: number): string => {
  if (!parentId) return '无';
  const findParent = (categories: Category[], targetId: number): Category | null => {
    for (const category of categories) {
      if (category.id === targetId) {
        return category;
      }
      const found = findParent(category.child, targetId);
      if (found) {
        return found;
      }
    }
    return null;
  };
  const parent = findParent(categoryList.value, parentId);
  return parent ? parent.name : '未知';
};

const handleInfoEdit = () => {
  if (selectedCategory.value) {
    showEditModal(selectedCategory.value.id);
  }
};

const handleDelete = () => {
  if (!selectedCategory.value) return;
  
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除分类"${selectedCategory.value.name}"吗？`,
    okText: '确认',
    cancelText: '取消',
    okButtonProps: { danger: true },
    onOk: async () => {
      try {
        const res = await delCategory(selectedCategory.value!.id);
        if (res.data.code === 200) {
          message.success('删除成功');
          selectedCategory.value = null;
          fetchCategoryList();
        } else {
          message.error(res.data.msg || '删除失败');
        }
      } catch (error) {
        console.error('删除分类失败:', error);
        message.error('删除失败，请稍后重试');
      }
    },
  });
};

onMounted(() => {
  fetchCategoryList();
});
</script>

<style scoped>
#categoryListPage {
  padding: 24px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.add-button {
  display: flex;
  align-items: center;
  gap: 4px;
}

.content {
  display: flex;
  gap: 24px;
}

.tree-container, .info-container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  padding: 20px;
  transition: all 0.3s ease;
}

.tree-container {
  flex: 4;
  min-width: 300px;
}

.info-container {
  flex: 6;
  min-width: 400px;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.category-tree {
  margin-top: 8px;
}

.category-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 0;
}

.category-icon {
  color: #1890ff;
}

.info-card {
  background-color: #f9f9f9;
  border-radius: 6px;
  padding: 16px;
  transition: all 0.3s ease;
}

.info-header {
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.info-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
  color: #333;
}

.info-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.info-item {
  display: flex;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px dashed #f0f0f0;
}

.info-item:last-child {
  border-bottom: none;
}

.label {
  color: #666;
  width: 100px;
  font-weight: 500;
}

.value {
  color: #333;
  flex: 1;
}

.empty-info {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 200px;
  color: #999;
  gap: 12px;
}

.empty-icon {
  font-size: 48px;
  color: #d9d9d9;
}

.info-actions {
  display: flex;
  gap: 8px;
}

/* 添加一些悬停效果 */
.category-item:hover {
  background-color: #f5f5f5;
  border-radius: 4px;
}

.info-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 响应式调整 */
@media (max-width: 768px) {
  .content {
    flex-direction: column;
  }
  
  .tree-container, .info-container {
    width: 100%;
  }
}
</style> 